<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
		<link rel="stylesheet" href="../util/bootstrap-3.3.7-dist/css/bootstrap.css">
    <style>
        /*@media screen and (max-device-width: 620px) {*/
        /*    section {*/
        /*        width: 96%;*/
        /*        padding: 0 2%;*/
        /*    }*/
        /*}*/

        /*@media screen and (min-width: 620px) {*/
        /*    section {*/
        /*        width:50%;*/
        /*        !*border: red 1px solid;*!*/
        /*        padding: 0 10px;*/
        /*    }*/
        /*}*/
        body{
            padding:30px;
        }
        .stumanager{

            margin-left: 15px;
            width: auto;
            height: 45px;
            font-size:34px;
            line-height:45px;
            background:white;
            border-bottom: 5px solid #e9fbdb;
            overflow: hidden;
        }
        .blue{
            background:white ;
        }
        .information{

            background:white ;
            margin-left: 15px;
        }
    </style>
		
</head>



<!--主体部分开始---------------------------------------------->
<body style="background:#e9fbdb  ">
<section style="background: white;">
    <div class="stumanager">学生管理系统</div></p>
    <div class="information">
    <p>学号:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="text" id="stuid"></p>
    <p>学生姓名:<input type="text" id="name"></p>
    <p>学生年龄:<input type="text" id="age"></p>
    <p>学生性别:<input type="radio" name="sex" id="male" checked value="男">男<input type="radio" id="female" name="sex"
                                                                               value="女">女</p>
    <p>所在班级:<input type="text" id="score"></p>
    <p>入园时间:<input type="text" id="Admissiontime" placeholder="年/月/日"></p>
    <p>家长姓名:<input type="text" id="parentsname"></p>
    <p>家庭住址:<input type="text" id="faddress"></p>
    </div>


    <button class="btn btn-success glyphicon glyphicon-plus" id="addstu">添加学生</button>&nbsp;&nbsp;&nbsp;
    <input type="text" id="text5" placeholder="请输入学生学号：">
    <input type="button" class="btn-info" id="Inquirestu" value="查询" style="outline: none">
    <br><br>


    <table class="table table-hover table-bordered blue" id="stuInfo" border="1" cellspacing="0" style="text-align: center">
    </table>
</section>

<script>
    let tab = document.getElementById("stuInfo");
    let addStu = document.getElementById("addstu");
    let name = document.getElementById("name");
    let age = document.getElementById("age");
    let score = document.getElementById("score");
    let sex = document.getElementsByName("sex");

    let stuid = document.getElementById("stuid");
    let Admissiontime = document.getElementById("Admissiontime");
    let parentsname = document.getElementById("parentsname");
    let faddress = document.getElementById("faddress");
    //记录修改时的下标值
    let index = null;
    //初始化数据先为null，之后会从localstorage里面获取数据
    let stuInfo = null;
    //渲染数组
    let render = function (stuInfo) {
        //首先重置table里面的内容，将其清空
        tab.innerHTML = '';
        //如果为0给它添加thead
        if (stuInfo.length !== 0) {
            let thead = '<tr class="mm"><td><b>学号</b></td><td><b>学生姓名</b></td><td><b>学生年龄</b></td><td><b>学生性别</b></td><td><b>所在班级</b></td><td><b>入园时间</b></td><td><b>家长姓名</b></td><td><b>家庭住址</b></td><td><b>操作</b></td></tr>';
            let tbody = '';
            let stLength =  Object.keys(stuInfo).length;
            for (let i = 0; i < stLength; i++) {
                tbody += `<tr>


            <td>${stuInfo[i].stuid}</td>

            <td>${stuInfo[i].name}</td>
            <td>${stuInfo[i].age}</td>
            <td>${stuInfo[i].sex}</td>
            <td>${stuInfo[i].score}</td>

            <td>${stuInfo[i].Admissiontime}</td>
            <td>${stuInfo[i].parentsname}</td>
            <td>${stuInfo[i].faddress}</td>
            <td><button class="btn btn-info"  onclick=editStu(${i})>修改</button>&nbsp;&nbsp;<button class="btn btn-danger" onclick=delStu(${i})>删除</button></td>
       </tr>`
            }
            tab.innerHTML += thead + tbody;
        } else {
            tab.innerHTML = '';
        }
    };
    //JSON和数组相互转换函数，自动检测，如果传入的是JSON,那就转为数组;如果传入的是数组就转为JSON
    let typeChange = function (a) {
        if (Array.isArray(a)) {
            let obj = {};
            for (let key in a) {
                obj[key] = a[key];
            }
            return obj;
        } else {
            let arr = [];
            for (let key in a) {
                arr[key] = a[key];
            }
            return arr;
        }
    };
    window.onload = function () {
        //第一次localStorage里面没有任何数据,所以做些初始化工作
        if (localStorage.stuInfo === undefined) {
            let info = {
                0: {
                    'stuid': '201901023',
                    'name': '小张',
                    'age': 20,
                    'sex': '男',
                    'score': '小班',
                    'Admissiontime': '2019/3/5',
                    'parentsname': '张无情',
                    'faddress': '成都市高新区'
                },
                1: {
                    'stuid': '201901023',
                    'name': '小刘',
                    'age': 20,
                    'sex': '男',
                    'score': '中班',
                    'Admissiontime': '2019/3/5',
                    'parentsname': '刘无情',
                    'faddress': '成都市高新区'
                },
                2: {
                    'stuid': '201901023',
                    'name': '小阳',
                    'age': 20,
                    'sex': '男',
                    'score': '大班',
                    'Admissiontime': '2019/3/5',
                    'parentsname': '阳无情',
                    'faddress': '成都市高新区'
                }
            };
            localStorage.stuInfo = JSON.stringify(info);//将数据转换为字符串存入localStorage
            stuInfo = typeChange(info)
        } else {
            stuInfo = typeChange(JSON.parse(localStorage.stuInfo))
        }
        render(stuInfo);//渲染出数据
    };
    //根据表单控件的值新建个学生对象 因为新增和修改都会用到，所以单独提取出来
    //该函数会返回建立好的学生对象
    let makeNewStu = function () {
        //获取单选框里的值
        let sexValue = null;
        for (let i = 0; i < sex.length; i++) {
            if (sex[i].checked === true) {
                sexValue = sex[i].value;
            }
        }
        //构成对象
        let newStu = {
            'stuid': stuid.value, 'name': name.value, 'age': age.value, 'sex': sexValue, 'score': score.value,
            'Admissiontime': Admissiontime.value, 'parentsname': parentsname.value, 'faddress': faddress.value
        };
        return newStu;
    };
    addStu.addEventListener('click', function () {
        if (addStu.innerHTML === '添加学生') {
            if (name.value === '' || age.value === '' || score.value === '') {
                alert('信息不能为空');
            } else {
                let newStu = makeNewStu();//创建一个新的学生对象
                //将对象推入stuInfo数组
                stuInfo.push(newStu);
                //重新渲染
                render(stuInfo);
                //更新本地存储的数据先转换为JSON对象，然后再转为字符串
                localStorage.stuInfo = JSON.stringify(typeChange(stuInfo));
                //清空文本框
                stuid.value = "";
                name.value = "";
                age.value = "";
                sex[0].checked = true;
                score.value = "";
                Admissiontime.value = "";
                parentsname.value = "";
                faddress.value = "";

            }
        } else {
            //下一步就是获取修改的信息
            let newInfo = makeNewStu();//直接调用该函数获取表单的值即可
            stuInfo.splice(index, 1, newInfo);//对数值进行修改
            render(stuInfo);//重新渲染
            //更新本地存储数据 先转换为JSON对象，然后转换为字符串
            localStorage.stuInfo = JSON.stringify(typeChange(stuInfo));
            addStu.innerHTML = '添加学生';
            //清空文本框
            stuid.value = "";
            name.value = "";
            age.value = "";
            score.value = "";
            sex[0].checked = true;
            Admissiontime.value = "";
            parentsname.value = "";
            faddress.value = "";
        }
    }, false);
    //如果使用3Q,可以直接使用on绑定事件，因为on默认自带事件委托，无论是一开始有的元素，还是后面新增的元素，都会被绑定事件
    let delStu = function (i) {
        if (window.confirm('确定是否删除此学生')) {
            stuInfo.splice(i, 1);//删除数组元素
            render(stuInfo);//重新渲染
            localStorage.stuInfo = JSON.stringify(typeChange(stuInfo));
        }
    };
    let editStu = function (i) {
        addStu.innerHTML = '确定修改';

        stuid.value = stuInfo[i].stuid;

        name.value = stuInfo[i].name;
        age.value = stuInfo[i].age;
        if (stuInfo[i].sex === '男') {
            sex[0].checked = true;
        } else {
            sex[1].checked = true
        }
        score.value = stuInfo[i].score;

        Admissiontime.value = stuInfo[i].Admissiontime;
        parentsname.value = stuInfo[i].parentsname;
        faddress.value = stuInfo[i].faddress;

        index = i;


    };
    //获取单元格
    var tabel2 = document.querySelectorAll("td");
    var Inquirestu = document.getElementById("Inquirestu");
    var text5 = document.getElementById("text5");
    var str = JSON.parse(localStorage.getItem('stuInfo'));
    var str1 = str;
    var strLength = Object.keys(str).length;
    let obj = {};

    //根据学号进行查询
   Inquirestu.addEventListener('click',function () {
       // alert(11);
       for (let i=0;i<strLength;i++){
           if (str[i].stuid==text5.value){
               obj = str[i];
               console.log(str[i]);
               str = {};
               str[0] = obj;
               console.log(str);
               render(str);
               str = str1;
               localStorage.setItem('stuInfo',JSON.stringify(str));
               break;
           }
       }
   });

    text5.oninput = function () {
        if(text5.value==''){
            render(str1);
        }
    }





</script>
</body>
</html>